package com.example.openthedoor;

import android.util.Log;

import androidx.lifecycle.ViewModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MyViewModel extends ViewModel {
    private String userID, userName, passWord, photoPath, message;
    private boolean success;
    private File photo;
    private FaceRepository faceRepository;
    private final String url = "http://120.78.72.189:5000/student";
    private String result;
    private JSONObject jsonObject;
    private Object String;

    public void init() {
        HashMap<String, String> user = new HashMap<String, String>();
        user.put("groupId", getUserName());
        user.put("image", getPhotoPath());
        user.put("userId", getUserID());
        this.faceRepository = new FaceRepository(user);
    }

    public void login(String userName, String passWord) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .get()
                        .url(url + "?username=" + userName + "&password=" + passWord)
                        .build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    setResult(Objects.requireNonNull(response.body()).string());
                    Log.e("Login", getResult());

                    jsonObject = new JSONObject(getResult());
                    setSuccess(jsonObject.getBoolean("success"));
                    if (getSuccess()) {
                        setPassWord(jsonObject.getString("password"));
                        setUserID(jsonObject.getString("userId"));
                        setUserName(jsonObject.getString("username"));
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void register(String userName, String passWord, String userID) {
//        RequestBody requestBody = new FormBody.Builder()
//                .add("username", userName)
//                .add("password", passWord)
//                .add("userId", userID)
//                .build();
        JSONObject json = new JSONObject();
        try {
            json.put("username", userName);
            json.put("password", passWord);
            json.put("userId", userID);
            String jsonStr = json.toString();
            RequestBody requestBody = RequestBody.create((MediaType) String,jsonStr);

            new Thread() {
                @Override
                public void run() {
                    super.run();
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .addHeader("content-type", "application/json")
                            .post(requestBody)
                            .url(url)
                            .build();
                    Call call = okHttpClient.newCall(request);
                    try {
                        Response response = call.execute();
                        setResult(Objects.requireNonNull(response.body()).string());
                        Log.e("Register", getResult());

                        jsonObject = new JSONObject(getResult());
                        setSuccess(jsonObject.getBoolean("success"));
                        if (getSuccess()) {
                            setPassWord(passWord);
                            setUserID(userID);
                            setUserName(userName);
                        } else {
                            setMessage(jsonObject.getString("message"));
                        }
                    } catch (IOException | JSONException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void update(String passWord) {
        JSONObject json = new JSONObject();
        try {
            json.put("username", getUserName());
            json.put("password", passWord);
            String jsonStr = json.toString();
            RequestBody requestBody = RequestBody.create((MediaType) String,jsonStr);

            new Thread() {
                @Override
                public void run() {
                    super.run();
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .addHeader("content-type", "application/json")
                            .put(requestBody)
                            .url(url)
                            .build();
                    Call call = okHttpClient.newCall(request);
                    try {
                        Response response = call.execute();
                        setResult(Objects.requireNonNull(response.body()).string());
                        Log.e("Update", getResult());

                        jsonObject = new JSONObject(getResult());
                        setSuccess(jsonObject.getBoolean("success"));
                        if (getSuccess()) {
                            setPassWord(passWord);
                        } else {
                            setMessage(jsonObject.getString("message"));
                        }
                    } catch (IOException | JSONException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void delete() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .delete()
                        .url(url + "?username=" + userName)
                        .build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    setResult(Objects.requireNonNull(response.body()).string());
                    Log.e("Delete", getResult());

                    jsonObject = new JSONObject(getResult());
                    setSuccess(jsonObject.getBoolean("success"));
                    if (getSuccess()) {
                        setPassWord(null);
                        setUserID(null);
                        setUserName(null);
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public String getPhotoPath() {
        return photoPath;
    }

    public void setPhotoPath(String photoPath) {
        this.photoPath = photoPath;
    }

    public File getPhoto() {
        return photo;
    }

    public void setPhoto(File photo) {
        this.photo = photo;
    }

    public String getUserID() {
        return userID;
    }

    public void setUserID(String userID) {
        this.userID = userID;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public boolean getSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean faceRegister() throws JSONException {
        return faceRepository.enroll(photoPath);
    }

    public boolean faceUpdate() throws JSONException {
        return faceRepository.update(photoPath);
    }

    public String faceSearch() throws JSONException {
        return faceRepository.search_face_token();
    }

    public boolean faceDelete() throws JSONException {
        return faceRepository.delete();
    }

    public void delay(int ms){
        try {
            Thread.currentThread();
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
